import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { marked } from 'marked';
import HTMLtoDOCX from 'html-to-docx';
import { JSDOM } from 'jsdom';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

class MarkdownToWord {
    constructor() {
        // 自定义Markdown渲染器
        this.renderer = new marked.Renderer();
        this.setupRenderer();
        
        // 设置 marked 选项
        marked.setOptions({
            renderer: this.renderer,
            gfm: true,
            breaks: true,
            sanitize: false
        });
    }

    setupRenderer() {
        // 标题处理
        this.renderer.heading = (text, level) => {
            return `<h${level} style="font-weight: bold;">${text}</h${level}>`;
        };

        // 列表处理
        this.renderer.list = (body, ordered) => {
            const type = ordered ? 'ol' : 'ul';
            return `<${type} style="margin-left: 20px;">${body}</${type}>`;
        };

        // 代码块处理
        this.renderer.code = (code, language) => {
            return `<pre style="background-color: #f4f4f4; padding: 10px; border-radius: 5px;"><code>${code}</code></pre>`;
        };

        // 表格处理
        this.renderer.table = (header, body) => {
            return `<table style="border-collapse: collapse; width: 100%;"><thead>${header}</thead><tbody>${body}</tbody></table>`;
        };
    }

    async convert(mdFilePath, outputPath) {
        try {
            // 转换为绝对路径
            const absoluteMdPath = path.resolve(mdFilePath);
            const absoluteOutputPath = path.resolve(outputPath);

            // 检查输入文件是否存在
            if (!fs.existsSync(absoluteMdPath)) {
                throw new Error(`找不到输入文件: ${absoluteMdPath}`);
            }

            // 确保输出目录存在
            const outputDir = path.dirname(absoluteOutputPath);
            if (!fs.existsSync(outputDir)) {
                fs.mkdirSync(outputDir, { recursive: true });
            }

            // 读取Markdown文件
            const mdContent = fs.readFileSync(absoluteMdPath, 'utf-8');

            // 转换为HTML
            const htmlContent = await marked.parse(mdContent);

            // 添加基本样式
            const fullHtml = `
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                    <style>
                        @font-face {
                            font-family: 'Arial';
                            font-style: normal;
                            font-weight: normal;
                        }
                        body { 
                            font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
                            color: #333;
                            background-color: #fff;
                            font-size: 12pt;
                        }
                        table { border-collapse: collapse; width: 100%; }
                        th, td { border: 1px solid #ddd; padding: 8px; }
                        code { background-color: #f4f4f4; padding: 2px 5px; }
                        h1, h2, h3, h4, h5, h6 { font-family: Arial, sans-serif; }
                    </style>
                </head>
                <body>
                    ${htmlContent}
                </body>
                </html>
            `;

            // 转换为Word文档，使用新的 html-to-docx 库
            const options = {
                orientation: 'portrait',
                margins: {
                    top: 1440, // 1 inch in twips
                    right: 1440,
                    bottom: 1440,
                    left: 1440
                },
                title: path.basename(mdFilePath, '.md'),
                font: {
                    family: 'Arial'
                },
                bullet: {
                    indent: 720 // 0.5 inches
                }
            };
            
            // html-to-docx 返回 Buffer
            const docxBuffer = await HTMLtoDOCX(fullHtml, null, options);
            
            // 写入文件
            fs.writeFileSync(absoluteOutputPath, docxBuffer);

            return true;
        } catch (error) {
            console.error('转换过程中出错:', error);
            return false;
        }
    }
}

export default MarkdownToWord;
